<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地址保存测试 - 简化版</title>
    <script src="js/vue-2.5.16.js"></script>
    <script src="js/axios-0.18.0.min.js"></script>
    <script src="js/host.js"></script>
    <script src="js/common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: #f5f5f5;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        input,
        select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
        }

        input:focus,
        select:focus {
            outline: none;
            border-color: #007cba;
        }

        button {
            width: 100%;
            padding: 15px;
            background: #007cba;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }

        button:hover {
            background: #005a87;
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .debug-info {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 15px;
            margin-top: 20px;
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }

        .success {
            color: #28a745;
            font-weight: bold;
        }

        .error {
            color: #dc3545;
            font-weight: bold;
        }

        .status {
            text-align: center;
            margin: 20px 0;
            padding: 15px;
            border-radius: 6px;
        }

        .status.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>

<body>
    <div id="app" class="container">
        <h1>🎯 地址保存测试</h1>

        <!-- 登录状态 -->
        <div v-if="!isLoggedIn" class="status error">
            请先登录系统
        </div>
        <div v-else class="status success">
            ✅ 已登录用户: {{ username }}
        </div>

        <!-- 地址表单 -->
        <form @submit.prevent="saveAddress">
            <div class="form-group">
                <label>收货人姓名 *</label>
                <input type="text" v-model="addressForm.receiver" required placeholder="请输入收货人姓名">
            </div>

            <div class="form-group">
                <label>手机号 *</label>
                <input type="text" v-model="addressForm.mobile" required placeholder="请输入11位手机号">
            </div>

            <div class="form-group">
                <label>固定电话（可选）</label>
                <input type="text" v-model="addressForm.tel" placeholder="格式：区号-号码，如：010-12345678">
                <small style="color: #666;">格式要求：区号-号码，如 010-12345678</small>
            </div>

            <div class="form-group">
                <label>省份 *</label>
                <select v-model="addressForm.province_id" required @change="getCities">
                    <option value="">请选择省份</option>
                    <option v-for="province in provinces" :value="province.id">{{ province.name }}</option>
                </select>
            </div>

            <div class="form-group">
                <label>城市 *</label>
                <select v-model="addressForm.city_id" required @change="getDistricts" :disabled="!cities.length">
                    <option value="">请选择城市</option>
                    <option v-for="city in cities" :value="city.id">{{ city.name }}</option>
                </select>
            </div>

            <div class="form-group">
                <label>区县 *</label>
                <select v-model="addressForm.district_id" required :disabled="!districts.length">
                    <option value="">请选择区县</option>
                    <option v-for="district in districts" :value="district.id">{{ district.name }}</option>
                </select>
            </div>

            <div class="form-group">
                <label>详细地址 *</label>
                <input type="text" v-model="addressForm.place" required placeholder="请输入详细地址">
            </div>

            <div class="form-group">
                <label>邮箱（可选）</label>
                <input type="email" v-model="addressForm.email" placeholder="请输入邮箱地址">
            </div>

            <button type="submit" :disabled="saveLoading">
                {{ saveLoading ? '保存中...' : '保存地址' }}
            </button>
        </form>

        <!-- 结果状态 -->
        <div v-if="result.message" :class="['status', result.success ? 'success' : 'error']">
            {{ result.message }}
        </div>

        <!-- 调试信息 -->
        <div class="debug-info" v-if="debugLog">{{ debugLog }}</div>
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                host: host,
                isLoggedIn: false,
                username: '',
                saveLoading: false,
                provinces: [],
                cities: [],
                districts: [],
                addressForm: {
                    receiver: '测试用户',
                    province_id: '',
                    city_id: '',
                    district_id: '',
                    place: '测试街道123号',
                    mobile: '13800138000',
                    tel: '010-12345678',
                    email: 'test@example.com'
                },
                result: { success: false, message: '' },
                debugLog: ''
            },
            mounted: function () {
                this.checkLogin();
                this.getProvinces();
            },
            methods: {
                log: function (message) {
                    const timestamp = new Date().toLocaleTimeString();
                    this.debugLog += `[${timestamp}] ${message}\n`;
                    console.log(`[${timestamp}]`, message);
                },

                checkLogin: function () {
                    var url = this.host + '/addresses/';
                    this.log('检查登录状态...');

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.log('登录检查响应: ' + JSON.stringify(response.data));
                            if (response.data.code === 0) {
                                this.isLoggedIn = true;
                                this.username = 'itcast_01';
                            }
                        })
                        .catch(error => {
                            this.log('登录检查失败，需要重新登录');
                            this.login();
                        });
                },

                login: function () {
                    var url = this.host + '/login/';
                    var loginData = {
                        username: 'itcast_01',
                        password: '12345678'
                    };

                    this.log('执行登录: ' + JSON.stringify(loginData));

                    axios.post(url, loginData, {
                        responseType: 'json',
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => {
                            this.log('登录响应: ' + JSON.stringify(response.data));
                            if (response.data.code === 0) {
                                this.isLoggedIn = true;
                                this.username = 'itcast_01';
                                this.log('✅ 登录成功！');
                            } else {
                                this.log('❌ 登录失败: ' + (response.data.errmsg || '未知错误'));
                            }
                        })
                        .catch(error => {
                            this.log('登录错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getProvinces: function () {
                    var url = this.host + '/areas/';
                    this.log('获取省份列表...');

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.log('省份响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.province_list) {
                                this.provinces = response.data.province_list;
                                this.log('✅ 成功获取 ' + this.provinces.length + ' 个省份');
                            }
                        })
                        .catch(error => {
                            this.log('获取省份错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getCities: function () {
                    if (!this.addressForm.province_id) return;

                    var url = this.host + '/areas/' + this.addressForm.province_id + '/';
                    this.log('获取城市列表，省份ID: ' + this.addressForm.province_id);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.log('城市响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.sub_data && response.data.sub_data.subs) {
                                this.cities = response.data.sub_data.subs;
                                this.districts = [];
                                this.addressForm.city_id = '';
                                this.addressForm.district_id = '';
                                this.log('✅ 成功获取 ' + this.cities.length + ' 个城市');
                            }
                        })
                        .catch(error => {
                            this.log('获取城市错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                getDistricts: function () {
                    if (!this.addressForm.city_id) return;

                    var url = this.host + '/areas/' + this.addressForm.city_id + '/';
                    this.log('获取区县列表，城市ID: ' + this.addressForm.city_id);

                    axios.get(url, {
                        responseType: 'json',
                        withCredentials: true
                    })
                        .then(response => {
                            this.log('区县响应: ' + JSON.stringify(response.data));
                            if (response.data && response.data.sub_data && response.data.sub_data.subs) {
                                this.districts = response.data.sub_data.subs;
                                this.addressForm.district_id = '';
                                this.log('✅ 成功获取 ' + this.districts.length + ' 个区县');
                            }
                        })
                        .catch(error => {
                            this.log('获取区县错误: ' + JSON.stringify(error.response ? error.response.data : '无响应'));
                        });
                },

                saveAddress: function () {
                    this.saveLoading = true;
                    this.result = { success: false, message: '' };
                    this.debugLog = '';

                    // 验证必填字段
                    if (!this.addressForm.receiver || !this.addressForm.place || !this.addressForm.mobile ||
                        !this.addressForm.province_id || !this.addressForm.city_id || !this.addressForm.district_id) {
                        this.result = { success: false, message: '❌ 请填写所有必填字段' };
                        this.saveLoading = false;
                        return;
                    }

                    // 验证手机号格式
                    if (!/^1[3-9]\d{9}$/.test(this.addressForm.mobile)) {
                        this.result = { success: false, message: '❌ 手机号格式不正确' };
                        this.saveLoading = false;
                        return;
                    }

                    // 验证固定电话格式（如果有值）
                    if (this.addressForm.tel && !/^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/.test(this.addressForm.tel)) {
                        this.result = { success: false, message: '❌ 固定电话格式不正确，应为：区号-号码，如 010-12345678' };
                        this.saveLoading = false;
                        return;
                    }

                    // 验证邮箱格式（如果有值）
                    if (this.addressForm.email && !/^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$/.test(this.addressForm.email)) {
                        this.result = { success: false, message: '❌ 邮箱格式不正确' };
                        this.saveLoading = false;
                        return;
                    }

                    // 创建纯数据对象
                    var addressData = JSON.parse(JSON.stringify({
                        receiver: this.addressForm.receiver,
                        province_id: this.addressForm.province_id,
                        city_id: this.addressForm.city_id,
                        district_id: this.addressForm.district_id,
                        place: this.addressForm.place,
                        mobile: this.addressForm.mobile,
                        tel: this.addressForm.tel,
                        email: this.addressForm.email,
                        title: this.addressForm.receiver
                    }));

                    this.log('📝 准备保存地址数据');
                    this.log('📋 原始表单数据: ' + JSON.stringify(this.addressForm));
                    this.log('🔍 纯数据对象: ' + JSON.stringify(addressData));
                    this.log('📞 tel字段类型: ' + typeof addressData.tel);
                    this.log('📞 tel字段值: "' + addressData.tel + '"');
                    this.log('📏 tel字段长度: ' + addressData.tel.length);

                    var url = this.host + '/addresses/create/';
                    this.log('🚀 发送请求到: ' + url);

                    axios.post(url, addressData, {
                        responseType: 'json',
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => {
                            this.log('📡 响应数据: ' + JSON.stringify(response.data));
                            if (response.data.code === 0) {
                                this.result = { success: true, message: '✅ 地址保存成功！' };
                                this.log('🎉 地址保存成功！');
                            } else {
                                this.result = { success: false, message: '❌ 保存失败: ' + (response.data.errmsg || '未知错误') };
                                this.log('💥 保存失败: ' + (response.data.errmsg || '未知错误'));
                            }
                        })
                        .catch(error => {
                            this.log('🔥 请求错误: ' + JSON.stringify({
                                message: error.message,
                                response: error.response ? error.response.data : '无响应',
                                status: error.response ? error.response.status : '无状态'
                            }));
                            this.result = { success: false, message: '❌ 网络错误，请查看调试信息' };
                        })
                        .finally(() => {
                            this.saveLoading = false;
                        });
                }
            }
        });
    </script>
</body>

</html>